package com.zgw.his.emr.parser;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.zgw.his.emr.model.DetailRecord;
import com.zgw.his.emr.model.MedicalRecord;
import com.zgw.his.emr.model.PageRecord;
import com.zgw.his.emr.model.RootRecord;

// xml生成器
public class XmlDumper extends XmlSign {
	private MedicalRecord record;
	private String xmlContent;
	Document document;
	Element rootElement;

	public XmlDumper(MedicalRecord record) {
		this.record = record;
	}

	// 生成xml内容
	public String dump() {
		document = DocumentHelper.createDocument();
		if (record instanceof RootRecord) {
			rootElement = createRoot((RootRecord) record);
			document.add(rootElement);
		}
		xmlContent = document.asXML();
		return xmlContent;
	}

	public Element createRoot(RootRecord rr) {
		Element root = DocumentHelper.createElement(M_RECORD);
		{
			root.addAttribute(P_IDENTIFIER, rr.getIdentifier());
			root.addAttribute(P_ROOT_TEMPLATE, rr.getRootTemlage());
		}

		// 创建页
		for (PageRecord pr : rr.getPageRecords()) {
			Element pageElement = createPage(pr);
			root.addText("\n");
			root.add(pageElement);
		}
		return root;
	}

	public Element createPage(PageRecord r) {
		Element page = DocumentHelper.createElement(M_PAGE);
		{
			page.addAttribute(P_TEMPLATE_ID, r.getTemplate().getIdentifier());
			page.addAttribute(P_PAGE_NUMBER, r.getPageNumber() + "");
		}

		// 创建记录明细
		for (DetailRecord d : r.getTemplate().getDetails()) {
			Element detailElement = createDetail(d);
			if (detailElement != null) {
				page.addText("\n");
				page.add(detailElement);
			}
		}
		return page;
	}

	public Element createDetail(DetailRecord r) {
		if (r.getText() == null || r.getText().equals(""))
			return null;
		Element el = DocumentHelper.createElement(M_DETAIL);
		{
			el.addAttribute(P_CODE, r.getCode());
			el.setText(r.getText());
		}
		return el;
	}

}
